<template>
  <span @click="click" :class="time != second ? 'disabled' : ''">{{ btn_text }}</span>
</template>
<script>
  export default {
    name: 'CCCountDown',
    props: {
      deftext: {
        type: String,
        default: '获取手机验证码'
      },
      second: {
        type: Number,
        default: 60
      }
    },
    data() {
      return {
        time: 60,
        timer: null
      };
    },
    computed: {
      btn_text() {
        return this.time !== this.second ? this.time + 's' : this.deftext;
      }
    },

    methods: {
      run(sec) {
        if (this.timer) return;
        if (sec) {
          this.time = sec;
        } else {
          this.time = this.second;
        }
        this.startTimer();
      },

      startTimer() {
        if (this.time > 0) {
          this.time--;
          this.timer = setTimeout(this.startTimer, 1000);
        } else {
          clearTimeout(this.timer);
          this.timer = null;
          this.time = this.second;
        }
      },

      click() {
        this.$emit('click');
      }
    },

    created() {}
  };
</script>
<style lang="scss" type="text/scss" scoped>
span {
  display: inline-block;
  color: white;
  background: $c1;
  text-align: center;
  min-width: 120px;
  cursor: pointer;
  border-radius: 4px;
}

.disabled {
  background: lightgray;
  pointer-events: none;
}
</style>
